﻿namespace ETestIT.UI
{
    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Core.Storage;
    using Domain.Entities;
    using Domain.Repositories;
    using Presentation;
    using StructureMap;

    public partial class Users : PageBase<Users>
    {
        private const string EditeduserKey = "editedUser";

        private ISessionStorage sessionStorage;
        private IUserRepository userRepository;

        protected void Page_Load(object sender, EventArgs e)
        {
            userAddEdit.Update += UserAddEditUpdate;

            userRepository = ObjectFactory.GetInstance<IUserRepository>();
            sessionStorage = ObjectFactory.GetInstance<ISessionStorage>();

            if (!IsPostBack)
                GetAllCandidates();
        }

        private void GetAllCandidates()
        {
            gvUsers.DataSource = userRepository.GetAll();
            gvUsers.DataBind();
        }

        protected void LnkEditCommand(object sender, CommandEventArgs e)
        {
            var userId = new Guid(e.CommandArgument.ToString());

            switch (e.CommandName)
            {
                case "UserEdit":
                    {
                        userAddEdit.SetModel(userRepository.GetById(userId));
                        userAddEdit.Visible = Visible;
                        sessionStorage.Set(EditeduserKey, userId);
                        GetAllCandidates();
                        break;
                    }
                case "UserDelete":
                    {
                        userRepository.Delete(userId);
                        GetAllCandidates();
                        break;
                    }
                default:
                    userAddEdit.Visible = false;
                    break;
            }
        }

        protected void BtnCreateNewUser_Clicked(object sender, EventArgs e)
        {
            userAddEdit.Visible = Visible;
        }

        public void UserAddEditUpdate(object sender, EventArgs e)
        {
            //TODO: check for existence by name

            User theUser;
            Action<User> theActionOnUser;

            if (sessionStorage.Contains(EditeduserKey))
            {
                theUser = userRepository.GetById(sessionStorage.Get<Guid>(EditeduserKey));
                theActionOnUser = u => { userRepository.Update(theUser); };
            }
            else
            {
                theUser = new User();
                theActionOnUser = u => { userRepository.Add(theUser); };
            }

            if (userAddEdit.IsInputValide())
            {
                userAddEdit.UpdateModelFromUserInput(theUser);
                theActionOnUser(theUser);
                userAddEdit.Visible = false;
                GetAllCandidates();

                if (sessionStorage.Contains(EditeduserKey))
                    sessionStorage.Remove(EditeduserKey);
            }
        }
    }
}